#!/bin/bash

ICONr='🔽'
ICONt='🔼'

# Interface
wired_interface=$(ip -o link show | awk -F': ' '{print $2}' | grep "^e" | head -n 1)
wireless_interface='wlan0'

# Wireless network
if [[ -d "/sys/class/net/${wireless_interface}" ]]; then
    wireless_ip_addr=$(ip addr show dev "${wireless_interface}" | awk '/inet / {print $2}' | cut -d'/' -f1)
    if [[ -n "${wireless_ip_addr}" ]]; then
        interface='wlan0'
    fi
fi

# Wired network
if [[ -d "/sys/class/net/${wired_interface}" ]]; then
    wired_ip_addr=$(ip addr show dev "${wired_interface}" | awk '/inet / {print $2}' | cut -d'/' -f1)
    if [[ -n "${wired_ip_addr}" ]]; then
        interface="${wired_interface}"
    fi
fi

# Get the number of bytes transmitted and received
if [[ -f /tmp/rx_bytes ]]; then
    read -r old_rx_bytes < /tmp/rx_bytes
else
    old_rx_bytes=0
fi
if [[ -f /tmp/tx_bytes ]]; then
    read -r old_tx_bytes < /tmp/tx_bytes
else
    old_tx_bytes=0
fi

rx_bytes=$(cat "/sys/class/net/${interface}/statistics/rx_bytes")
tx_bytes=$(cat "/sys/class/net/${interface}/statistics/tx_bytes")
printf %d\\n "${rx_bytes}" > /tmp/rx_bytes
printf %d\\n "${tx_bytes}" > /tmp/tx_bytes

# Calculate the number of bytes transmitted and received per second
rx_speed=$(( rx_bytes-old_rx_bytes ))
tx_speed=$(( tx_bytes-old_tx_bytes ))

printf "${ICONr} %sB ${ICONt} %sB│" "$(numfmt --to=iec ${rx_speed})" "$(numfmt --to=iec ${tx_speed})"

# EOF

